package com.kaili.basic.service.impl;


import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaili.basic.enums.StatusEnum;
import com.kaili.basic.mapper.DeviceMapper;
import com.kaili.basic.mapper.DeviceOnlineMapper;
import com.kaili.basic.pojo.dto.*;
import com.kaili.basic.pojo.entity.MdmDeviceEntity;
import com.kaili.basic.enums.DeviceEunm;
import com.kaili.basic.pojo.entity.MdmDeviceSignEntity;
import com.kaili.basic.enums.DeviceStatusEunm;
import com.kaili.basic.pojo.entity.MdmDeviceOnline;
import com.kaili.basic.pojo.vo.*;
import com.kaili.basic.service.IMdmDeviceOnlineService;
import com.kaili.common.response.CommonStatus;

import com.kaili.common.response.ResponseData;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.DateUtil;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.common.util.UUIDUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kaili.basic.service.IDeviceSignService;
import com.kaili.basic.mapper.DeviceSignMapper;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
*  service实现类
* @author:zhouyijian
* @Time: 2019-07-24
* @Copyright: ©  杭州凯立通信有限公司 版权所有
* @Warning: 本内容仅限于公司内部传阅,禁止外泄或用于其它商业目的
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class DeviceSignServiceImpl extends ServiceImpl<DeviceSignMapper, MdmDeviceSignEntity>  implements IDeviceSignService {

    @Autowired
    DeviceSignMapper deviceSignMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IMdmDeviceOnlineService deviceOnlineService;

    @Autowired
    private DeviceOnlineMapper deviceOnlineMapper;

    @Override
    public Page<MdmDeviceSignDetailVO> queryPageListDetail(MdmDeviceSignQueryDto dto) {
        Page<MdmDeviceSignDetailVO> page = new Page<MdmDeviceSignDetailVO>();
        List<MdmDeviceSignDetailVO>  result=getSignRecordDetail(dto);
        page.setRecords(result);
        return page;
    }

    @Override
    public ResponseData doCreateDeviceSign(MdmDeviceOnlineAddDto dto) {
        Date date = new Date();
        String token = UUIDUtil.getUUId();
        if(dto==null){
            return responseData(CommonStatus.DEVICE_DATA_EMPTY,null);
        }
        //1.判断设备存在、是否启用
        MdmDeviceVO deviceVO =deviceMapper.getIsActionByImei(dto.getImei());
        if(deviceVO==null){
            return responseData(CommonStatus.DEVICE_NOT_EXISTS,null);
        }
        if(deviceVO.getIsAction().equals(DeviceStatusEunm.DEVICE__OFF)){
            return responseData(CommonStatus.DEVICE_NOT_ACTION,null);
        }
        //获取token值
        Object result =redisTemplate.opsForValue().get(dto.getToken());
        //第一次或者重新登录生成token
        if(result==null&&dto.getIsFirstLogin()==true||result!=null&&dto.getIsFirstLogin()==true){
            //1设备签到
            redisTemplate.opsForValue().set(token,dto.getImei(),15*60,TimeUnit.SECONDS);  //设置十五分钟过期
            Integer employeeId= LoginDetailUtils.getCurrentEmployeeId();
            MdmDeviceSignEntity entity = new MdmDeviceSignEntity();
            entity.setSignTime(date);
            entity.setImei(dto.getImei());
            entity.setCreateBy(employeeId);
            entity.setCreateTime(date);
            entity.setLongitude(dto.getLongitude());
            entity.setLatitude(dto.getLatitude());
            entity.setRdStatus(DeviceStatusEunm.NORMAL.getCode());
            deviceSignMapper.insert(entity);
            //2设备在线
            MdmDeviceOnline deviceOnline =new MdmDeviceOnline();
            BeanUtils.copyProperties(dto,deviceOnline);
            deviceOnline.setRdStatus(StatusEnum.NORMAL.getKey());
            deviceOnline.setFacilityId(deviceVO.getId().longValue());
            deviceOnline.setDeviceStatusId(103L);//已启用
            deviceOnline.setOnlineStatusId(DeviceEunm.DEVICE_ONLINE.getCode().longValue());
            deviceOnlineMapper.insert(deviceOnline);
            //3设备告警
            MdmDeviceOnlineUpdateDto deviceOnlineUpdateDto = new MdmDeviceOnlineUpdateDto();
            BeanUtils.copyProperties(deviceOnline,deviceOnlineUpdateDto);
            deviceOnlineUpdateDto.setRdStatus(StatusEnum.NORMAL.getKey());
            deviceOnlineUpdateDto.setImei(dto.getImei());
            deviceOnlineUpdateDto.setFacilityId(deviceVO.getId().longValue());
            deviceOnlineUpdateDto.setOnlineStatusId(DeviceEunm.DEVICE_ONLINE.getCode());
            deviceOnlineService.updateMdmDeviceOnline(deviceOnlineUpdateDto);
            return responseData(CommonStatus.ADD_OK,token);
        }
        //token不失效且不是第一次登录更新签到信息
        if(result!=null&&dto.getIsFirstLogin()==false){
            updateDeviceSignByImei(dto);  //更新设备信息
            return responseData(CommonStatus.UPDATE_OK, null);
        }

        return responseData(CommonStatus.DEVICE_TOKEN_DISABLE,null);
    }


    @Override
    public List<MdmDeviceSignDetailVO>  queryListByCondition(MdmDeviceSignQueryDto dto) {
        List<MdmDeviceSignDetailVO>   result=getSignRecordDetail(dto);
        return result;
    }

    @Override
    public List<MdmDeviceSignVO> querySignTotal(MdmDeviceSignQueryDto dto) {
        MdmDeviceSignEntity entity = new MdmDeviceSignEntity();
        BeanUtils.copyProperties(dto,entity);
        List<MdmDeviceSignVO> result =deviceSignMapper.querySignTotal(entity);
        return result;
    }

    @Override
    public RestStatus updateDeviceSignByImei(MdmDeviceOnlineAddDto dto) {
        Date date =new Date();
        Integer employeeId= LoginDetailUtils.getCurrentEmployeeId();
        MdmDeviceSignEntity entity = new MdmDeviceSignEntity();
        MdmDeviceVO deviceVO =deviceMapper.getIsActionByImei(dto.getImei());
        entity.setModifyTime(date);
        entity.setLongitude(dto.getLongitude());
        entity.setLatitude(dto.getLatitude());
        entity.setModifyBy(employeeId);
        entity.setId(deviceVO.getId());
        entity.setRdStatus(DeviceStatusEunm.NORMAL.getCode());
        deviceSignMapper.updateById(entity);
        //更新设备在线信息
        MdmDeviceOnline deviceOnline =new MdmDeviceOnline();
        BeanUtils.copyProperties(dto,deviceOnline);
        deviceOnline.setModifyBy(employeeId);
        deviceOnline.setModifyTime(date);
        deviceOnline.setFacilityId(deviceVO.getId().longValue());
        deviceOnline.setOnlineStatusId(DeviceEunm.DEVICE_ONLINE.getCode().longValue());
        deviceOnlineMapper.updateMdmDeviceOnline(deviceOnline);
        //更新设备告警
        MdmDeviceOnlineUpdateDto deviceOnlineUpdateDto = new MdmDeviceOnlineUpdateDto();
        BeanUtils.copyProperties(deviceOnline,deviceOnlineUpdateDto);
        deviceOnlineUpdateDto.setImei(dto.getImei());
        deviceOnlineUpdateDto.setRdStatus(StatusEnum.NORMAL.getKey());
        deviceOnlineUpdateDto.setFacilityId(deviceVO.getId().longValue());
        deviceOnlineUpdateDto.setOnlineStatusId(DeviceEunm.DEVICE_ONLINE.getCode());
        deviceOnlineService.updateMdmDeviceOnline(deviceOnlineUpdateDto);
        return CommonStatus.UPDATE_OK;

    }

    @Override
    public List<MdmDeviceSignVO> querySignRecord() {
        return deviceSignMapper.querySignRecord();
    }

    /**
     * @Desc:  设备位置--是否将设备在线管理中的最新位置加入计算
     * @author: shenliqiang
     * @Time: 2019/7/29 14:41
     * @param dto
     * @return java.lang.String[][]
     */

    @Override
    public List<MdmDeviceSignLocationVo> queryDeviceLocation(MdmDeviceSignLocationDto dto) {
        if(dto.getDate()==null){//参数中无date则默认为当天
            dto.setDate(Calendar.getInstance().getTime());
        }
        return  this.deviceSignMapper.queryDeviceLocation(dto);
    }
    /**
     * @Desc:  设备轨迹
     * @author: shenliqiang
     * @Time: 2019/7/29 14:41
     * @param dto
     * @return java.lang.String[][]
     */

    @Override
    public String[][] queryDeviceTrack(MdmDeviceSignLocationDto dto) {
        if(dto.getDate()==null){//参数中无date则默认为当天
            dto.setDate(Calendar.getInstance().getTime());
        }
        List<MdmDeviceSignTrackVo> list = this.deviceSignMapper.queryDeviceTrack(dto);
        String[][] strings = new String[list.size()][2];
        Iterator<MdmDeviceSignTrackVo> iterator = list.iterator();
        int i = 0;
        while (iterator.hasNext()){
            MdmDeviceSignTrackVo vo = iterator.next();
            strings[i] = new String[]{vo.getLongitude(),vo.getLatitude()};
            i++;
        }
        return strings;
    }
        /**
         * @Desc:签到信息
         * @author:zhouyijian
         * @time: 2019/8/6 13:17
         * @param dto
         * @return: java.util.List<com.kaili.basic.pojo.vo.MdmDeviceSignDetailVO>
         */
    private List<MdmDeviceSignDetailVO> getSignRecordDetail(MdmDeviceSignQueryDto dto){
        MdmDeviceEntity device = new MdmDeviceEntity();
        MdmDeviceSignEntity entity = new MdmDeviceSignEntity();
        if(DeviceEunm.IS_SIGN.getCode().equals(dto.getIsSign())){  //已签
            dto.setStartTime(DateUtil.getDayBenginTime(dto.getDateTime())); //开始时间
            dto.setEndTime(DateUtil.getDayLastTime(dto.getDateTime())); //结束时间
            BeanUtils.copyProperties(dto,entity);
            List<MdmDeviceSignDetailVO>  result =deviceSignMapper.getSignDetail(entity);
            return  result;
        }//未签
            BeanUtils.copyProperties(dto,device);
            device.setStartTime(DateUtil.getDayBenginTime(dto.getDateTime())); //开始时间
            device.setEndTime(DateUtil.getDayLastTime(dto.getDateTime()));  //结束时间
            device.setIsAction(DeviceStatusEunm.DEVICE_ON.getCode());
            List<MdmDeviceSignDetailVO>  result =deviceMapper.queryUnSignDetail(device);
           return result;
    }

    /**
     * @Desc:组装返回数据
     * @author:zhouyijian
     * @time: 2019/8/8 11:38
     * @param commonStatus
     * @param object
     * @return: com.kaili.common.response.ResponseData
     */
    private ResponseData responseData(CommonStatus commonStatus,Object object){
        ResponseData responseData = new ResponseData();
        responseData.setData(object);
        responseData.setMessage(commonStatus.getReasonPhrase());
        responseData.setStatus(commonStatus.value());
        return responseData;
    }
}
